package com.gxa.employment.interceptor;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gxa.employment.common.JsonConvert;
import com.gxa.employment.common.ManagerThreadLocal;
import com.gxa.employment.entity.pojo.Manager;
import com.gxa.employment.exception.BizException;
import com.gxa.employment.exception.ErrorMessage;

import com.gxa.employment.utils.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 拦截器 使用aop实现  登录的权限校验
 * @Author:
 * @DateTime: 2025/3/6 15:48
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 访问controller前，进行的校验
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //获取token
        String token = request.getHeader("authorization");
        System.out.println(token);
        //判断是否为空
        if (StringUtils.isEmpty(token)) {
            throw new BizException(ErrorMessage.TOKEN_LOSE);
        }
        token = token.substring(7);

        //解析获取token时间
        if (JwtUtil.isExpire(token)) {
            throw new BizException(ErrorMessage.TOKEN_EXPIRED);
        }

        //没有异常，进行存储载荷信息
        String managerJson = JwtUtil.getClaim(token, "manager");
        String roleId = JwtUtil.getClaim(token, "roleId");
        //读取数据
        Manager manager = JsonConvert.read(managerJson, Manager.class);

        //校验token是否正确
        try {
            //没有异常就是正确的
            JwtUtil.verify(token);
            if(redisTemplate.opsForValue().get("token:"+manager.getManagerPhone())==null){
                throw new BizException(ErrorMessage.TOKEN_EXPIRED);
            }
        } catch (Exception e) {
            throw new BizException(ErrorMessage.TOKEN_ERROR);
        }



        //储存
        ManagerThreadLocal.set(manager);
        //获取uri
        String uri = request.getRequestURI();
        System.out.println("uri:" + uri);
        SetOperations<String, Object> opsForSet = redisTemplate.opsForSet();
        Set<Object> permission = opsForSet.members("role:" + roleId);
        System.out.println("redis获取的权限信息：" + permission);
        //如果权限为null，
        if (permission == null) {
            //返回异常，强制退出
            throw new BizException(ErrorMessage.NO_PERMISSION);
        }
        //鉴权，路径
        for (Object o : permission) {
            if (uri.contains((CharSequence) o)){
                return true;
            }
        }
        throw new BizException(ErrorMessage.NO_PERMISSION);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ManagerThreadLocal.remove();
    }
}
